/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hvtt.web.controller;

import com.hvtt.web.connection.Command;
import static com.hvtt.web.connection.Command.sqlStoredProcedure;
import com.hvtt.web.connection.WEBConnection;
import com.hvtt.web.connection.WEBParamCollection;
import com.hvtt.web.models.C_dangtin;
import com.hvtt.web.models.C_doixe;
import com.hvtt.web.models.C_dongxe;
import com.hvtt.web.models.C_hangxe;
import com.hvtt.web.models.C_search;
import com.hvtt.web.models.C_thietbi_nhom;
import com.hvtt.web.models.SearchModel;
import com.hvtt.web.models.Si_quocgia;
import com.hvtt.web.models.Si_tinh;
import com.hvtt.web.utilities.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class SearchController implements Serializable{
      private WEBConnection DAL=new WEBConnection();
    
    private SearchModel item =new SearchModel();
   
    
    private List<Si_tinh> lstTinh=new ArrayList<>();
    private List<C_hangxe> lstHangXe=new ArrayList<>();
    private List<C_doixe> lstDoiXe=new ArrayList<>();
    private List<C_dongxe> lstDongXe=new ArrayList<>();
    private List<SearchModel> lstDanhSachCacXeXemNhieuNhat=new ArrayList();
    private List<String> lstGiaCaoNhat=new ArrayList<>();
    
    private List<String> lstNamSanXuat=new ArrayList<>();
    private List<String> lstSoKMDaDi=new ArrayList<>();
    
    private int soMauTin=10;
    private int trang=1;
    private int iTrang=1;
    private int tongSoMauTin=0;
    
    
    public List<Si_tinh> findAllTinh() throws SQLException
    {
        if(lstTinh.size()<=0)
        {
            WEBParamCollection Params=new WEBParamCollection();
            Params.add("VN");
            lstTinh= DAL.executeQuery("Select* from SI_Tinh where QuocGiaID=? order by SI_Tinh.ThuTu asc",Command.sqlText,Params,Si_tinh.class);
        }
        return lstTinh;
    }
    
    public List<C_hangxe> findAllHangXe() throws SQLException
    {
        if(lstHangXe.size()<=0)
            lstHangXe=DAL.executeQuery("Select* from C_HangXe where C_HangXe.TrangThai=1", C_hangxe.class);
        return lstHangXe;
    }
    public List<String> findAllNamSanXuat()
    {
        if(lstNamSanXuat.size()<=0)
        {
            List<String> lst=new ArrayList<>();

            int iYear = Calendar.getInstance().get(Calendar.YEAR);
            for(int i=iYear;i>=iYear-40;i--)
                lstNamSanXuat.add(String.valueOf(i));
        }
        return lstNamSanXuat;
    }
    public List<String> findAllGiaCaoNhat()
    {
        if(lstGiaCaoNhat.size()<=0)
        {
            List<String> lst=new ArrayList<>();

            //int iYear = Calendar.getInstance().get(Calendar.YEAR);
            int i=1000;
            while(i<=100000)
            {
                lstGiaCaoNhat.add(String.valueOf(i));
                if(i<25000)
                    i+=1000;
                else
                    i+=5000;
            }
        }
        return lstGiaCaoNhat;
    }
    public List<String> findAllSoKMDaDi()
    {
        if(lstSoKMDaDi.size()<=0)
        {
            List<String> lst=new ArrayList<>();

            //int iYear = Calendar.getInstance().get(Calendar.YEAR);
            int i=10;
            while(i<=10000)
            {
                lstSoKMDaDi.add(String.valueOf(i));
                if(i<100)
                    i+=10;
                else if(i<1000)
                    i+=100;
                else
                    i+=1000;
            }
        }
        return lstSoKMDaDi;
    }
    public List<C_doixe> findAllDoiXe() throws SQLException
    {
       
             WEBParamCollection Params=new WEBParamCollection();
             Params.add(this.getItem().getHangXeID());
             lstDoiXe =DAL.executeQuery("Select* from C_doixe where C_doixe.HangXeID=? and C_doixe.TrangThai=1", Command.sqlText, Params, C_doixe.class);
        
        return lstDoiXe;
    }
    
     
    public List<C_dongxe> findAllDongXe() throws SQLException
    {
        if(lstDongXe.size()<=0)
            lstDongXe= DAL.executeQuery("Select* from C_DongXe where C_DongXe.TrangThai=1", C_dongxe.class);
        return lstDongXe;
    }
    
    public List<SearchModel> findAllDanhSachCacXeXemNhieuNhat() throws SQLException
    {
//        if(lstDanhSachCacXeXemNhieuNhat.size()<=0)
            lstDanhSachCacXeXemNhieuNhat= DAL.executeQuery("{call PG_Load_C_DangTin_DanhSachCacXeDuocXemNhieuNhat()}", SearchModel.class);
        return lstDanhSachCacXeXemNhieuNhat;
    }
    
    
    
    public SearchModel getItem()
    {
        return item;
    }
    
    
    public List<SearchModel> searchResult() throws SQLException
    {
     
        List<SearchModel>lstResult=new ArrayList();
        if(!FacesContext.getCurrentInstance().isPostback())
        {
            C_search c =new C_search();
            c.setDoiXeID(this.item.getDoiXeID());
            c.setGiaCaoNhat(this.item.getGiaCaoNhat());
            c.setHangXeID(this.item.getHangXeID());
            c.setTinhID(this.item.getTinhID());
            c.setNamXanXuat(this.item.getNamSanXuat());
            c.setSoKMDaDi(this.item.getSoKMDaDi());
            c.setKey1(String.valueOf(this.item.getTinhTrangXe()));
            c.setKey2(Utilities.getLanguages("NewAndUsed"));
            add_SearchToSession(c);

            List<SearchModel> lst;
            WEBParamCollection Params=WEBParamCollection.getInstance();
            Params.add(this.item.getTinhTrangXe());
            Params.add(this.item.getHangXeID());
            Params.add(this.item.getDoiXeID());
            Params.add(this.item.getGiaCaoNhat());
            Params.add(this.item.getTinhID());
            Params.add(this.item.getNamSanXuat());
            Params.add(this.item.getSoKMDaDi());
            Params.add(this.item.getLoaiXeBan());
            Params.add(this.item.getLoaiXe());
            lst=DAL.executeQuery("{call PG_Load_C_DangTin_Search_Cars(?,?,?,?,?,?,?,?,?)}",sqlStoredProcedure,Params, SearchModel.class);
            
            tongSoMauTin=lst.size();
           
            int i=0;
            if(trang>1)
                i=(trang-1)*soMauTin-1;
            int i1=0;
          
            if(i>=lst.size())
            {
                trang=iTrang;
                
                if(trang>1)
                    i=(trang-1)*soMauTin-1;
            }
            while(i<lst.size()&& i1<soMauTin)
            {
                lstResult.add(lst.get(i));
                
                i++;
                i1++;
            }
        }
    return lstResult;        
    }
    
     public void cmdPhanTrangSearch_Click(ActionEvent event) throws IOException, SQLException {
        iTrang=trang;
        String strTrang=String.valueOf(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("pg"));
            if("".equals(strTrang.trim()))
            {
                trang=1;
            }
            else{
                try
                {
                    switch (strTrang) {
                        case "-":
                            if(trang<=1)
                                trang=1;
                            else
                                trang--;
                            break;
                        case "+":
                            if(trang<1)
                                trang=1;
                            else
                                trang++;
                            break;
                        default:
                            trang=Integer.parseInt(strTrang);
                            break;
                    }
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
                    
                }
                catch(NumberFormatException | IOException ex) {trang=1;}
                    }
      }
    
    private void add_SearchToSession(C_search searchitem)
    {
        FacesContext context = FacesContext.getCurrentInstance();  

        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();  
        HttpSession httpSession = request.getSession(false); 
        List<C_search> lst=(List<C_search>)httpSession.getAttribute(Utilities.getSS_Search_Data());
        if(lst==null)
        {
            lst=new ArrayList<>();
        }
        lst.add(searchitem);
        httpSession.setAttribute(Utilities.getSS_Search_Data(), lst);
    }
    
    public List<C_search> findAllSearchbySession()
    {
       FacesContext context = FacesContext.getCurrentInstance();  

        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();  
        HttpSession httpSession = request.getSession(false); 
        List<C_search> lst=(List<C_search>)httpSession.getAttribute(Utilities.getSS_Search_Data());
        if(lst==null)
        {
            lst=new ArrayList<>();
        }
        return lst;
    }
    public List<C_search> findAllSearchbyUser() throws SQLException
    {
        WEBParamCollection Params=new WEBParamCollection();
        Params.add(Sys_NguoiDungController.findUser().getUserID());
        List<C_search> lst= DAL.executeQuery("Select* from c_search where UserID=?",Command.sqlText,Params,C_search.class);
        return lst;
    }
    public void addSearchToDatabase(C_search searchitem) throws SQLException
    {
        WEBParamCollection Params=new WEBParamCollection();
        Params.add("Add");
        Params.add(searchitem.getID());
        Params.add(searchitem.getUserID());
        Params.add(searchitem.getHangXeID());
        Params.add(searchitem.getDoiXeID());
        Params.add(searchitem.getNamXanXuat());
        Params.add(searchitem.getGiaCaoNhat());
        Params.add(searchitem.getTinhID());
        Params.add(searchitem.getSoKMDaDi());
        Params.add(searchitem.getKey1());
        Params.add(searchitem.getKey2());
        DAL.executeUpdate("{call Proc_c_Search_In_Up_Del(?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
    }
    public void DeleteSearchDatabase(C_search searchitem) throws SQLException
    {
        WEBParamCollection Params=new WEBParamCollection();
        Params.add("Delete");
        Params.add(searchitem.getID());
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        Params.add("");
        DAL.executeUpdate("{call Proc_c_Search_In_Up_Del(?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
    }
    
    
    
    
    public void Search_Cars_New_Click(ActionEvent event) throws IOException, SQLException {
        long lHangXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID"));
        long lDoiXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("DoiXeID"));
        int iLoaiXe=Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("LoaiXe"));
        double dblGiaCaoNhat=Double.parseDouble(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("GiaCaoNhat"));
        String strTinhID=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID").toString();
        
        trang=1;
        iTrang=1;
               
        
        this.item.Reset();
        this.item.setTinhID(strTinhID);
        this.item.setHangXeID(lHangXeID);
        this.item.setDoiXeID(lDoiXeID);
        this.item.setGiaCaoNhat(dblGiaCaoNhat);
        this.item.setTinhTrangXe(0);
        this.item.setLoaiXe(iLoaiXe);
                    
          
       FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
    }
    
    public void Search_Cars_Specific_Click(ActionEvent event) throws IOException, SQLException {
        long lHangXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID"));
        long lDoiXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("DoiXeID"));
        int iNamSanXuat=Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("NamSanXuat"));
        //String strTinhID=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID").toString();
        
            trang=1;
            iTrang=1;
        
            this.item.Reset();
            this.item.setNamSanXuat(iNamSanXuat);
            this.item.setHangXeID(lHangXeID);
            this.item.setDoiXeID(lDoiXeID);
            this.item.setTinhTrangXe(0);
                    
          
       FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
    }
    
    public void Search_Cars_Used_Click(ActionEvent event) throws IOException, SQLException {
        long lHangXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID"));
        long lDoiXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("DoiXeID"));
        double dblGiaCaoNhat=Double.parseDouble(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("GiaCaoNhat"));
        String strTinhID=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID").toString();
        int iLoaiXe=Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("LoaiXe"));
        
        trang=1;
        iTrang=1;
        
        this.item.Reset();
        this.item.setTinhID(strTinhID);
        this.item.setHangXeID(lHangXeID);
        this.item.setDoiXeID(lDoiXeID);
        this.item.setGiaCaoNhat(dblGiaCaoNhat);
        this.item.setTinhTrangXe(1);
        this.item.setLoaiXe(iLoaiXe);
                    
          
       FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
    }
     public void Search_cars_dealer_Click(ActionEvent event) throws IOException, SQLException {
        String LoaiXeBan=String.valueOf(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID"));
        String strTinhID=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TinhID").toString();
        
        trang=1;
        iTrang=1;
        
        this.item.Reset();
            this.item.setTinhID(strTinhID);
            this.item.setLoaiXeBan(LoaiXeBan);
         this.item.setTinhTrangXe(5);
                    
          
       FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
    }
     public void Search_cars_CheckValue_Click(ActionEvent event) throws IOException, SQLException {
        long lHangXeID=Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID"));
        String NamSanXuat=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("NamSanXuat").toString();
        String SoKMDaDi=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("SoKMDaDi").toString();
        
        trang=1;
        iTrang=1;
        
        this.item.Reset();
            this.item.setNamSanXuat(Integer.parseInt(NamSanXuat));
            this.item.setSoKMDaDi(Double.parseDouble(SoKMDaDi));
            this.item.setHangXeID(lHangXeID);
         this.item.setTinhTrangXe(6);
                    
          
       FacesContext.getCurrentInstance().getExternalContext().redirect("/searchResult.html");
    }
     
     
     
    
     public void cmd_search_cars_new_doixe_Click(ActionEvent event) throws IOException, SQLException {
          this.item.setHangXeID(Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID").toString()));
          trang=1;
          iTrang=1;
         // RequestContext.getCurrentInstance().execute("update=\"pnDoiXe\"");
      }
     public void cmd_search_cars_used_doixe_Click(ActionEvent event) throws IOException, SQLException {
         trang=1;
         iTrang=1;
          this.item.setHangXeID(Long.parseLong(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("HangXeID").toString()));
         // RequestContext.getCurrentInstance().execute("update=\"pnDoiXe\"");
      }

    /**
     * @return the soMauTin
     */
    public int getSoMauTin() {
        return soMauTin;
    }

    /**
     * @param soMauTin the soMauTin to set
     */
    public void setSoMauTin(int soMauTin) {
        this.soMauTin = soMauTin;
    }

    /**
     * @return the trang
     */
    public int getTrang() {
        return trang;
    }

    /**
     * @param trang the trang to set
     */
    public void setTrang(int trang) {
        this.trang = trang;
    }

    /**
     * @return the tongSoMauTin
     */
    public int getTongSoMauTin() {
        return tongSoMauTin;
    }

    /**
     * @param tongSoMauTin the tongSoMauTin to set
     */
    public void setTongSoMauTin(int tongSoMauTin) {
        this.tongSoMauTin = tongSoMauTin;
    }
     
     
}
